/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registration.web;

import static com.registration.ManagedBean.addErrorMessage;
import static com.registration.ManagedBean.addInfoMessage;
import com.registration.SearchManagedBean;
import com.registration.core.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.appfuse.webapp.util.FacesUtils;

/**
 * @date May 22, 2012
 *
 * @author ggutierrez
 */
public class SearchRegistrationBean extends SearchManagedBean {

    private String firstName;
    private String middleName;
    private String lastName;
    private String secondLastName;
    private String memberId;
    private List<Category> categories;
    private Category category;
    private List<Country> countries;
    private Country residence;
    private Stage currentStage;
    private MemberVerification memberVerification;
    private String categoryString;
    private String countryString;
    private String branch;

    public SearchRegistrationBean() {
    }

    @Override
    public void reset() {
        firstName = null;
        middleName = null;
        lastName = null;
        secondLastName = null;
        memberId = null;
        category = null;
        residence = null;
        memberVerification = null;
        categoryString = null;
        countryString = null;
        branch = null;
        super.reset();
    }

    @Override
    public String cancel() {
        return "success";
    }

    public String init() {
        reset();
        categories = getManager().findCategories(null);
        countries = getManager().findCountries();
        return "success";
    }

    public String execute() {
        List<Attendee> attendees = getManager().findAttendees(firstName, middleName, lastName, secondLastName, memberId, categoryString, countryString, memberVerification, currentStage, branch);
        setResults(FacesUtils.wrap(attendees));
        if (getResults() == null || getResults().isEmpty()) {
            addErrorMessage("No se encontraron registros.");
            return "fail";
        } else {
            return "success";
        }
    }

    public String confirm() {
        Date confirmationDate = new Date();
        List<Attendee> attendees = (List<Attendee>) FacesUtils.unwrapOnlyMarked((Collection) this.getResults());

        if (attendees != null && !attendees.isEmpty()) {
            for (Attendee attendee : attendees) {
                attendee.setConfirmationDate(confirmationDate);
                attendee.setCurrentStage(Stage.PRESENTE);
                getManager().store(attendee);
            }
            addInfoMessage("Registros Confirmados.");
        }

        return execute();
    }

    public String cleanRoomAssignment() {
        List<Attendee> attendees = (List<Attendee>) FacesUtils.unwrapOnlyMarked((Collection) this.getResults());
        if (attendees == null || (attendees != null && attendees.isEmpty())) {
            addErrorMessage("No hay registros seleccionados");
            return "success";
        }
        // Know the rooms
        if (attendees != null && !attendees.isEmpty()) {
            for (Attendee attendee : attendees) {
                attendee.getLodging().setRoom(null);
                getManager().store(attendee);
            }
        }

        return execute();
    }

    public String roomAssignment() {
        List<Attendee> attendees = (List<Attendee>) FacesUtils.unwrapOnlyMarked((Collection) this.getResults());
        if (attendees == null || (attendees != null && attendees.isEmpty())) {
            addErrorMessage("No hay registros seleccionados");
            return "success";
        }
        List<Attendee> attendeesWithoutRoom = new ArrayList();
        // Know the rooms
        if (attendees != null && !attendees.isEmpty()) {
            for (Attendee attendee : attendees) {
                if (attendee.getLodging().getRoom() == null && attendee.getRoomPlan() != null) {
                    attendeesWithoutRoom.add(attendee);
                }
            }
        }
        Map<Integer, List<Attendee>> rooms = new HashMap<Integer, List<Attendee>>();
        for (Attendee attendee : attendeesWithoutRoom) {
            if (rooms.containsKey(attendee.getRoomPlan().getBeds())) {
                List<Attendee> list = rooms.get(attendee.getRoomPlan().getBeds());
                list.add(attendee);
                rooms.put(attendee.getRoomPlan().getBeds(), list);
            } else {
                List<Attendee> list = new ArrayList<Attendee>();
                list.add(attendee);
                rooms.put(attendee.getRoomPlan().getBeds(), list);
            }
        }

        Hotel hotel = getManager().findHotels() != null ? getManager().findHotels().get(0) : null;

        if (hotel != null) {
            for (Map.Entry entry : rooms.entrySet()) {
                Integer room = (Integer) entry.getKey();
                List<Attendee> guests = (List<Attendee>) entry.getValue();
                int assignation = 1;
                int group = hotel.getRooms() != null ? hotel.getRooms().intValue() + 1 : 1;
                hotel.setRooms(group);
                getManager().store(hotel);

                for (Attendee guest : guests) {                    
                    if (assignation > room.intValue()) {
                        assignation = 1;
                        group++;
                        hotel.setRooms(group);
                        getManager().store(hotel);
                    }
                    String roomNumber = group + "GH" + assignation;
                    guest.getLodging().setRoom(roomNumber);
                    getManager().store(guest);
                    assignation++;
                }
            }
        }
        return execute();
    }
    
    public String copy() throws CloneNotSupportedException {
        List<Attendee> attendees = (List<Attendee>) FacesUtils.unwrapOnlyMarked((Collection) this.getResults());
        if (attendees == null || (attendees != null && attendees.isEmpty())) {
            addErrorMessage("No hay registros seleccionados");
            return "success";
        }
        if (attendees != null && !attendees.isEmpty() && attendees.size() > 1) {
            addErrorMessage("Seleccione sólo un registro");
            return "success";
        }
        Attendee attendee = attendees.get(0);
        Attendee newAttendee = (Attendee)attendee.clone();
        newAttendee.setId(null);
        getManager().store(newAttendee);
        newAttendee.setCategory(null);
        getManager().store(newAttendee);
        
        addInfoMessage("Registro copiado");
        return execute();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getSecondLastName() {
        return secondLastName;
    }

    public void setSecondLastName(String secondLastName) {
        this.secondLastName = secondLastName;
    }

    public String getMemberId() {
        return memberId;
    }

    public void setMemberId(String memberId) {
        this.memberId = memberId;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public List<Country> getCountries() {
        return countries;
    }

    public void setCountries(List<Country> countries) {
        this.countries = countries;
    }

    public Country getResidence() {
        return residence;
    }

    public void setResidence(Country residence) {
        this.residence = residence;
    }

    public Stage getCurrentStage() {
        return currentStage;
    }

    public void setCurrentStage(Stage currentStage) {
        this.currentStage = currentStage;
    }

    public MemberVerification getMemberVerification() {
        return memberVerification;
    }

    public void setMemberVerification(MemberVerification memberVerification) {
        this.memberVerification = memberVerification;
    }

    public String getCategoryString() {
        return categoryString;
    }

    public void setCategoryString(String categoryString) {
        this.categoryString = categoryString;
    }

    public String getCountryString() {
        return countryString;
    }

    public void setCountryString(String countryString) {
        this.countryString = countryString;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }        
}
